package socksproxy.netty.proxy_wangZha.proxy1;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.util.Iterator;
import java.util.Map;

/**
 * 目标服务器业务处理
 */
public class Proxy1Handler extends ChannelInboundHandlerAdapter {

	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(">>>>>>>>ACTIVE>>>>>>>>");
        System.out.println(ctx.read());
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    	System.out.println(123);
        String uuid = ctx.channel().id().asLongText();
        ProxyGatewayService.addGatewayChannel(uuid, (SocketChannel)ctx.channel());
        System.out.println("装载Channel集合连接" + uuid);
    	System.out.println("客户端请求代理服务器1的数据是:"+msg);
    	System.out.println("代理服务器建立网闸1通道传递请求......");
 /*   	ctx.writeAndFlush("代理服务器正在请求数据请等待").sync();
    	ctx.close().sync();*/
    	Map<String, Channel> map = ProxyGatewayService.getChannels();
    	System.out.println("当前数组"+map.keySet().size());
    	Iterator<String> it = map.keySet().iterator();
        //
        if(map.keySet().size()<2){
    	EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
        	System.out.println("連接網閘!");
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                	ChannelPipeline pipeline = ch.pipeline();
    				pipeline.addLast("frameDecoder",
    						new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0,
    								4, 0, 4));
    				pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
    				pipeline.addLast("encoder",
							new StringEncoder(CharsetUtil.UTF_8));
                }
            });
            // Start the client.
            ChannelFuture f = b.connect("192.168.50.246", 5566).sync();
            f.channel().writeAndFlush(msg);
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    System.out.println("===========数据发送成功==========");
                }
            });
            // Wait until the connection is closed.
            //f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
        }else{
        	int i=0;
    		while (it.hasNext()) {
    			System.out.println("遍历次数"+(i++));
    		     String key = it.next();
    		     Channel obj = map.get(key);
    		     System.out.println("channel id is: " + key);
    		     System.out.println("channel客户端地址: " + obj.remoteAddress()+"ss:"+obj.read());
    		     System.out.println("channel连接状态: " + obj.isActive());
    		    // obj.writeAndFlush("hello, it is Server test header ping");
    		     //obj.close();
    		     obj.writeAndFlush(msg).addListener(new ChannelFutureListener() {
    		         @Override
    		         public void operationComplete(ChannelFuture future) throws Exception {
    		             if (future.isSuccess()) {
    		                 System.out.println("发送成功!");
    		                 map.remove(key);
    		                 
    		             } else {
    		            	 map.remove(key);
    		                 System.out.println("发送失败!");
    		             }
    		         }
    		     });
    		 }
        	 System.out.println("剩余的集合个数:"+map.keySet().size());
        	 if(map.keySet().size()>0){
        		 map.clear();
        		 System.out.println("剩余的集合个数:"+map.keySet().size());
        	 }
        }
    }
/**
 * 
 * @param msg 服务器返回的数据
 * @param map 加载的客户端连接
 * @param it 遍历的连接集合
 */

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(">>>>>>>>IN-ACTIVE>>>>>>>>");
        closeOnFlush(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        closeOnFlush(ctx.channel());
    }

    /**
     * Closes the specified channel after all queued write requests are flushed.
     */
    static void closeOnFlush(Channel ch) {
        if (ch.isActive()) {
            ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }
}